package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.ResultCodeEnum;
import com.atguigu.yygh.common.config.YyghException;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.hosp.ScheduleQueryVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author zhmwi
 * @Date 2021/7/8
 * @Dersciption
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private BaseMapper baseMapper;
    //上传排班
    @Override
    public void save(Map<String, Object> paramMap) {
        //将map转换为json
        String scheduleJsonStr = JSONObject.toJSONString(paramMap);
        //将json转换为对象
        Schedule schedule = JSONObject.parseObject(scheduleJsonStr,Schedule.class);
        //根据医院编号+排班编号查询排班信息
        Schedule targetSchedule =
                scheduleRepository.getSchduleByHoscodeAndHosScheduleId(schedule.getHoscode(),schedule.getHosScheduleId());
        if (targetSchedule == null) {
            //插入
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setStatus(1);
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }else{
            //更新
            targetSchedule.setUpdateTime(new Date());
            targetSchedule.setIsDeleted(0);
            targetSchedule.setStatus(1);
            scheduleRepository.save(targetSchedule);
        }
    }

    //带条件带分页查询排班
    @Override
    public Page<Schedule> selectPage(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //0为第一页
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo,schedule);
        schedule.setIsDeleted(0);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()//构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符串
                .withIgnoreCase(true);
        //创建实例
        Example<Schedule> example = Example.of(schedule, matcher);
        Page<Schedule> pages = scheduleRepository.findAll(example,pageable);
        return pages;
    }

    //删除排班
    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule targetSchedule = scheduleRepository.getSchduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (targetSchedule != null){
            scheduleRepository.deleteById(targetSchedule.getHosScheduleId());
        }
    }

    //根据医院编号和科室编号 查询排班规则数据
    @Override
    public Map<String, Object> getScheduleRule(long page, long limit, String hoscode, String depcode) {
        //1.根据查询条件 分页查询统计规则数据
        //1.1 设置查询条件
         Criteria criteria =
                 Criteria.where("hoscode").is(hoscode)
                          .and("depcode").is(depcode);
        //1.2 分组统计
        Aggregation aggregation = Aggregation.newAggregation(
                //1.3 匹配筛选条件
                Aggregation.match(criteria),//筛选条件

                //1.4 分组统计
                Aggregation.group("workDate")//分组字段
                        //分组统计结果
                        .first("workDate").as("workDate")
                        //统计号源数量
                        .count().as("docCount")
                        //统计预约总数
                        .sum("reservedNumber").as("reservedNumber")
                        //统记当前可预约数
                        .sum("availableNumber").as("availableNumber"),

                //1.5 排序
                Aggregation.sort(Sort.Direction.ASC, "workDate"),

                //1.6 分页
                Aggregation.skip((page - 1) * limit),

                Aggregation.limit(limit)
        );

        //封装统计分析查询对象
        //（1）参数规则
        //（2）输入对象
        //（3）输出对象
        AggregationResults<BookingScheduleRuleVo> aggregate
                = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);

        //拿到统计结果
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregate.getMappedResults();

        //2.根据查询条件 查询统计规则数据(获取total) 根据医院code 科室code
        Aggregation totalAggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );

        //封装统计分析查询对象
        AggregationResults<BookingScheduleRuleVo> aggregateTotal =
                mongoTemplate.aggregate(totalAggregation, Schedule.class, BookingScheduleRuleVo.class);

        //拿到统计结果
        List<BookingScheduleRuleVo> bookingScheduleRuleTotal = aggregateTotal.getMappedResults();

        int total = bookingScheduleRuleTotal.size();

        //3.借助工具算出周几
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }
        //4.封装数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList",bookingScheduleRuleVoList);
        result.put("total",total);
        //5.数据补全
        //获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        //其他基础数据
        HashMap<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosName);
        result.put("baseMap",baseMap);
        return result;
    }

    //查询详细排班
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        List<Schedule> scheduleList
                = scheduleRepository.getSchduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDate());
        scheduleList.stream().forEach(schedule -> {
            this.packageSchedule(schedule);
        });
        return scheduleList;
    }

    //根据id查询排班详情
    @Override
    public Schedule getScheduleById(String id) {
        Schedule schedule = scheduleRepository.findById(id).get();
        return schedule;
    }

    //根据排班id查询预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        //获取排班信息
        Schedule schedule = this.getScheduleById(scheduleId);
        if (schedule == null){
            throw new YyghException();
        }
        //获取医院信息
        Hospital hospital = hospitalService.getHospitalByHoscode(schedule.getHoscode());
        if (hospital == null) {
            throw new YyghException();
        }
        //获取科室信息
        Department department = departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode());
        if (department == null){
            throw new YyghException();
        }
        //封装信息
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        scheduleOrderVo.setHoscode(hospital.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(department.getDepcode());
        scheduleOrderVo.setDepname(department.getDepname());
        schedule.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());//剩余号源数量
        scheduleOrderVo.setTitle(schedule.getTitle());//医师 主任 副主任
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());//排班日期
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());//上午 下午


        BookingRule bookingRule = hospital.getBookingRule();
        //退号截止日期
        // (就诊前一天为-1 当天为0)
        Integer quitDay = bookingRule.getQuitDay();
        DateTime quiteTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plus(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quiteTime.toDate());

        //挂号开始时间  每天8:30 之后才可以约任意时间段的号
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //挂号截止时间  只能预约未来十天的号
        DateTime cycleTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(cycleTime.toDate());


        //当天停止挂号时间  每天11:30 之前可以约任意时间段的号
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());



        return scheduleOrderVo;
    }

    //下单 -- 更新排班记录
    @Override
    public void updateSchedule(Schedule schedule) {
        scheduleRepository.save(schedule);
    }

    //封装排班详情其他值 医院名称、科室名称、日期对应星期
    private void packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",hospitalService.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",
                departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }
    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

}
